<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Server-sent events demo</title>
</head>
<body>
<button>Close the connection</button>

<ul>
</ul>

<!--
<ol id="list">
</ol>
-->

<script>
    const eventList = document.querySelector('ul');
    const button = document.querySelector('button');
    const evtSource = new EventSource('sse.php');

    console.log('withCredentials = ' + evtSource.withCredentials);
    console.log('readyState = ' + evtSource.readyState);
    console.log('url = ' + evtSource.url);

    // console.log('Hi！')

    button.onclick = _ => {
        console.log('Connection closed.');
        evtSource.close();
    };

    evtSource.onopen = _ =>  console.log("Connection to server opened.")
    evtSource.onerror = _ => console.log('EventSource failed.')

    function addItem1(content){
        eventList.innerHTML += '<li>' + content + '</li>';
    }

    function addItem2(content){
        const newElement = document.createElement('li');
        // newElement.textContent = content;
        newElement.innerHTML = content;
        eventList.appendChild(newElement);
    }

    evtSource.onmessage = e => addItem1('Server MSG: ' + e.data);

    evtSource.addEventListener('time', e => addItem2(`Server Time: ${JSON.parse(e.data).time}`), false);
    evtSource.addEventListener('ping', e => addItem2(`ping @ ${JSON.parse(e.data).time}`), false);
</script>
</body>
</html>
